package com.ruicar.afs.cloud.apply.pre.loan.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.apply.common.entity.ApplyCustBaseInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOprRecord;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.entity.ChannelUrgentConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyReportCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.OrderOprCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.vo.OrderMngVO;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.parameter.commom.enums.OrderOprType;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 订单管理
 * @author: sijun.yu
 * @date: 2020/5/19 13:41
 */
@RequestMapping(value = "/orderMng")
@Slf4j
@RestController
@AllArgsConstructor
public class OrderMngController {

    private final ApplyReportService reportService;
    private final ApplyOprRecordService oprRecordService;
    private final ApplyOrderInfoService orderInfoService;
    private final ChannelUrgentConfigService channelUrgentConfigService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplyOprRecordService applyOprRecordService;

    /**
     * 进件申请-订单管理
     *
     * @return
     */
    @PostMapping(value = "/getLoanApplyList")
    @ApiOperation("进件申请-订单管理")
    public IResponse<List<OrderMngVO>> getLoanApplyList(@RequestBody QueryCondition<ApplyReportCondition> condition) {
        Map map = new HashMap();
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        if ("admin".equals(SecurityUtils.getUsername())) {
            return IResponse.success(null);
        }
        IPage<OrderMngVO> list = reportService.getLoanApplyList(page, condition.getCondition());
        log.info("info:{}", list);
        List<OrderMngVO> records = list.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(orderMngVO -> {
                //查询加急数据
                List<ApplyOprRecord> applyOprRecords = applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                        .eq(ApplyOprRecord::getApplyNo, orderMngVO.getApplyNo()).eq(ApplyOprRecord::getApplyType, String.valueOf(OrderOprType.URGENT)));
                if (CollectionUtil.isNotEmpty(applyOprRecords)) {
                    orderMngVO.setIsUrgent(WhetherEnum.YES.getCode());
                } else {
                    orderMngVO.setIsUrgent(WhetherEnum.NO.getCode());
                }
                //查询复议记录
                List<ApplyOprRecord> applyOprRecordList = applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                        .eq(ApplyOprRecord::getApplyNo, orderMngVO.getApplyNo()).eq(ApplyOprRecord::getApplyType, String.valueOf(OrderOprType.RECONSIDER)));
                if (CollectionUtil.isNotEmpty(applyOprRecordList)) {
                    orderMngVO.setIsReconsider(WhetherEnum.YES.getCode());
                } else {
                    orderMngVO.setIsReconsider(WhetherEnum.NO.getCode());
                }
            });
        }
        String channelId = SecurityUtils.getUser().getUserExtInfo().getString("channelId");
        ChannelUrgentConfig urgentConfig = this.channelUrgentConfigService.getOne(Wrappers.<ChannelUrgentConfig>query().lambda()
                .eq(StringUtil.isNotEmpty(channelId), ChannelUrgentConfig::getChannelId, Long.valueOf(channelId)));
        if (ObjectUtil.isNotNull(urgentConfig)) {
            //获取每月加急次数
            int surplusNumbers = urgentConfig.getSurplusNumbers();
            map.put("surplusNumbers", surplusNumbers);
        }

        map.put("loanList", list);
        return IResponse.success(map);
    }

    /**
     * 进件申请-订单管理
     *
     * @return
     */
    @PostMapping(value = "/delete")
    @ApiOperation("进件申请-订单管理")
    public IResponse delete(@RequestBody ApplyReportCondition condition) {

        ApplyOrderInfo orderInfo = orderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda().
                eq(StringUtil.isNotEmpty(condition.getApplyNo()), ApplyOrderInfo::getApplyNo, condition.getApplyNo()));
        if (ObjectUtil.isNotNull(orderInfo)) {
            this.orderInfoService.removeById(orderInfo);
        }
        return IResponse.success("删除成功");
    }


    /**
     * 保存加急信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/saveUrgent")
    @ApiOperation("保存加急信息")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_opr_record", allEntries = true)
    public IResponse saveUrgent(@ModelAttribute OrderOprCondition condition) {
        ApplyOprRecord oprRecord = new ApplyOprRecord();
        ApplyOprRecord one = this.oprRecordService.getOne(Wrappers.<ApplyOprRecord>query().lambda().eq(ApplyOprRecord::getApplyNo, condition.getApplyNo()));
        if (ObjectUtil.isNotNull(one)) {
            throw new AfsBaseException("不允许重复加急");
        }
        ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getCustBaseInfo(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        if (ObjectUtil.isNotNull(custBaseInfo)) {
            oprRecord.setCustName(custBaseInfo.getCustName());
            oprRecord.setCertNo(custBaseInfo.getCertNo());
        }
        oprRecord.setApplyNo(condition.getApplyNo());
        oprRecord.setApplyType(OrderOprType.URGENT);
        oprRecord.setApplyReason(condition.getUrgentReason());
        oprRecord.setCreateTime(new Date());
        oprRecord.setCreateBy(SecurityUtils.getUsername());
        oprRecordService.save(oprRecord);
        String channelId = SecurityUtils.getUser().getUserExtInfo().getString("channelId");
        ChannelUrgentConfig urgentConfig = this.channelUrgentConfigService.getOne(Wrappers.<ChannelUrgentConfig>query().lambda()
                .eq(StringUtil.isNotEmpty(channelId), ChannelUrgentConfig::getChannelId, Long.valueOf(channelId)));
        if (ObjectUtil.isNotNull(urgentConfig)) {
            int surplusNumbers = urgentConfig.getSurplusNumbers();
            surplusNumbers--;
            urgentConfig.setSurplusNumbers(surplusNumbers);
            this.channelUrgentConfigService.updateById(urgentConfig);
        }
        return IResponse.success(Boolean.TRUE);
    }

    /**
     * 保存撤回信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/saveBack")
    @ApiOperation("保存撤回信息")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_opr_record", allEntries = true)
    public IResponse saveBack(@ModelAttribute OrderOprCondition condition) {
        ApplyOprRecord applyOprRecord = oprRecordService.getOne(Wrappers.<ApplyOprRecord>query()
                .lambda().eq(StringUtil.isNotEmpty(condition.getApplyNo()), ApplyOprRecord::getApplyNo, condition.getApplyNo())
                .eq(ApplyOprRecord::getApplyType, String.valueOf(OrderOprType.BACK)));
        if (ObjectUtil.isNull(applyOprRecord)) {
            applyOprRecord = new ApplyOprRecord();
        }
        ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getCustBaseInfo(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        if (ObjectUtil.isNotNull(custBaseInfo)) {
            applyOprRecord.setCustName(custBaseInfo.getCustName());
            applyOprRecord.setCertNo(custBaseInfo.getCertNo());
        }
        applyOprRecord.setApplyNo(condition.getApplyNo());
        applyOprRecord.setApplyType(OrderOprType.BACK);
        applyOprRecord.setApplyReason(condition.getBackReason());
        applyOprRecord.setCreateTime(new Date());
        applyOprRecord.setCreateBy(SecurityUtils.getUsername());
        oprRecordService.saveOrUpdate(applyOprRecord);

        return IResponse.success(Boolean.TRUE);
    }

    /**
     * 订单复制信息
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/saveCopy")
    @ApiOperation("订单复制信息")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_opr_record", allEntries = true)
    public IResponse saveCopy(@ModelAttribute OrderOprCondition condition) {
        ApplyOprRecord oprRecord = new ApplyOprRecord();
        ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getCustBaseInfo(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        if (ObjectUtil.isNotNull(custBaseInfo)) {
            oprRecord.setCustName(custBaseInfo.getCustName());
            oprRecord.setCertNo(custBaseInfo.getCertNo());
        }
        oprRecord.setApplyNo(condition.getApplyNo());
        oprRecord.setApplyType(OrderOprType.COPY);
        oprRecord.setCreateTime(new Date());
        oprRecord.setCreateBy(SecurityUtils.getUsername());
        oprRecordService.save(oprRecord);

        // 重新生成一个申请编号，并保存对应的数据
        String applyNO = reportService.saveCopyOrderInfo(condition.getApplyNo());
        return IResponse.success(applyNO);
    }

    /**
     * 订单操作列表
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "getOrderOprList")
    @ApiOperation("订单操作列表")
    public IResponse<List<OrderMngVO>> getOrderOprList(@RequestBody QueryCondition<OrderOprCondition> condition) {

        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<OrderMngVO> list = reportService.getOrderOprList(page, condition.getCondition());
        return IResponse.success(list);
    }

    /**
     * 转单
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/transferData")
    @ApiOperation("转单")
    public IResponse transferData(@RequestBody OrderOprCondition condition) {
        ApplyOprRecord applyOprRecord = new ApplyOprRecord();
        ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getCustBaseInfo(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        if (ObjectUtil.isNotNull(custBaseInfo)) {
            applyOprRecord.setCustName(custBaseInfo.getCustName());
            applyOprRecord.setCertNo(custBaseInfo.getCertNo());
        }
        applyOprRecord.setApplyNo(condition.getApplyNo());
        applyOprRecord.setCreateBy(SecurityUtils.getUsername());
        applyOprRecord.setCreateTime(new Date());
        applyOprRecord.setApplyType(OrderOprType.TRANSFER);
        this.oprRecordService.save(applyOprRecord);
        //更新订单表的createBy,也就是录单员,
        ApplyOrderInfo orderInfoByApplyNo = this.orderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        //草稿时，转单更新操作人信息,修订暂停时，不可更新
        if (ApplyConstants.APPLY_STATUS_DRAFT.equals(orderInfoByApplyNo.getApplyStatus())) {
            orderInfoByApplyNo.setCreateBy(condition.getCreateBy());
        }
        orderInfoByApplyNo.setUpdateTime(condition.getUpdateTime());
        boolean b = this.orderInfoService.updateById(orderInfoByApplyNo);
        if (b) {
            return IResponse.success("转单成功");
        }
        return IResponse.success("转单失败");
    }
}
